import React, { useEffect, useState } from 'react'
import { Button, ButtonProps, Form, Input, message, Modal, ModalProps, Space } from 'antd'
import { ServerResult, UserPermission } from '../../../server/interface';
import { api_permission } from '../../apis';
import { updatePermission } from '../../store';

export interface PermModalProps {
    modalProps?: ModalProps;
    perm?: UserPermission;
    onOk?: () => void;
    buttonProps?: ButtonProps;
    children?: React.ReactNode;
}
export const PermModal = (props: PermModalProps) => {
    const { buttonProps = {}, modalProps = {}, perm, onOk, children } = props;
    const [form] = Form.useForm();
    const [visible, setVisible] = useState(false);
    const isUpdate = !!perm?.key;

    useEffect(function () {
        if (visible) {
            if (perm) {
                form.setFieldsValue(perm);
            } else {
                form.resetFields();
            }
        }
    }, [perm, visible])

    const onFinish = () => {
        form.validateFields().then(async (values: UserPermission) => {
            let res: ServerResult<any>
            if (isUpdate) {
                res = await api_permission.update({ ...values, key: perm?.key })
            } else {
                res = await api_permission.create([{ ...values }])
            }
            if (res.success) {
                setVisible(false);
                message.success('保存成功');
                updatePermission();
                onOk?.();
            }
        })
    }

    const title = isUpdate ? '修改' : '创建';
    return <>
        <Button {...buttonProps} onClick={() => setVisible(true)}>{children || title}</Button>
        <Modal {...modalProps}
            title={ title }
            open={visible}
            onCancel={() => setVisible(false)}
            footer={null}
        >
            <Form form={form} onFinish={onFinish} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} >
                <Form.Item label="权限ID" name="key" rules={[{ required: true, message: '请输入权限ID' }]} required>
                    <Input placeholder="请输入权限ID" disabled={isUpdate} />
                </Form.Item>
                <Form.Item label="权限名称" name="name" required rules={[{ required: true, message: '请输入权限名称' }]}>
                    <Input placeholder="请输入权限名称" />
                </Form.Item>
                <Form.Item label="权限描述" name="desc">
                    <Input placeholder="请输入权限描述" />
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
                    <Space>
                        <Button type="primary" htmlType="submit">{title}</Button>
                        <Button onClick={() => setVisible(false)}>取消</Button>
                    </Space>
                </Form.Item>
            </Form>
        </Modal>
    </>
}